package com.sand.dao.imp;

import com.sand.dao.IBaseDao;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.List;

@Repository(value = "baseDao")
public class BaseDao extends HibernateTemplate implements IBaseDao {
/**
 *
 *
 * @author <achao1441470436@gmail.com>
 * @since 2021/11/27/027 15:06
 */
    //注入sessionFactory
    @Override
    @Autowired
    public void setSessionFactory(SessionFactory sessionFactory) {
        super.setSessionFactory(sessionFactory);
    }

    /**
     * 添加实体对象
     *
     * @param obj
     * @return
     */
    @Override
    public boolean addObject(Object obj){
        Serializable save = super.save(obj);
        if(save!=null)return true;
        return false;
    }

    /**
     * 删除实体对象
     *
     * @param obj
     * @return
     */
    @Override
    public boolean delObject(Object obj) {
        try {
            super.delete(obj);
            return true;
        } catch (DataAccessException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 删除集合中所有的实体对象
     *
     * @param list
     * @return
     */
    @Override
    public boolean delAllObject(List list) {
        try {
            super.deleteAll(list);
            return true;
        } catch (DataAccessException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 修改实体对象
     *
     * @param obj
     * @return
     */
    @Override
    public boolean updateObject(Object obj) {
        try {
            super.update(obj);
            return true;
        } catch (DataAccessException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据id查询实体对象
     *
     * @param id
     * @return
     */
    @Override
    public Object queryObjectById(Class cls,int id) {
        return super.get(cls, id);
    }

    /**
     * 根据hql查询 ,返回 list实体对象集合
     * 例:"from TUserEntity t where t.loginName=?0 and t.password=?1",name,pwd
     *
     * @param hql
     * @return
     */
    @Override
    public List queryObject(String hql,Object ...param) {
        return super.find(hql, param);
    }

    /**
     * 分页查询
     * 参考文档:https://blog.csdn.net/u012881904/article/details/51308367/
     *
     * @param dc
     * @return
     */
    @Override
    public List queryObjectLimit(DetachedCriteria dc, int begin, int pageSize) {
        return super.findByCriteria(dc, begin, pageSize);
    }

    /**
     * 通用查询
     * 参考文档:https://blog.csdn.net/u012881904/article/details/51308367/
     *
     * @param dc
     * @return
     */
    @Override
    public List queryObjectCommon(DetachedCriteria dc) {
        return super.findByCriteria(dc);
    }
}
